<?php

/**
 * This is the model class for table "alt_user".
 *
 * The followings are the available columns in table 'alt_user':
 * @property integer $id
 * @property string $first_name
 * @property string $middle_name
 * @property string $last_name
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $picture
 * @property string $birthday
 * @property string $country
 * @property string $address
 * @property string $tele
 * @property string $fax
 * @property string $web
 * @property string $status
 */
class User extends CActiveRecord {
   /**
    * Returns the static model of the specified AR class.
    * @param string $className active record class name.
    * @return User the static model class
    */
   public $new_password;
   public $repeat_password;
   public $role;

   public static function model($className = __CLASS__) {
      return parent::model($className);
   }

   /**
    * @return string the associated database table name
    */
   public function tableName() {
      return 'alt_user';
   }

   /**
    * @return array validation rules for model attributes.
    */
   public function rules() {
      // NOTE: you should only define rules for those attributes that
      // will receive user inputs.
      return array(
          array('username, password, email,first_name,', 'required'),
          array('first_name, middle_name, last_name, password, email', 'length', 'max' => 255),
          array('username', 'match', 'pattern' => '/^[0-9A-Za-z\.]+$/', 'message' => 'Username can contain only letters and numbers', 'on' => 'step_two'),
          // array('password', 'ext.EPasswordStrength', 'min' => 7),
          array('tele, fax', 'numerical', 'integerOnly' => true, 'min' => 0),
          array('email', 'unique', 'className' => 'user', 'attributeName' => 'email', 'message' => 'This email already exists.'),
          array('birthday, address, web,country', 'safe'),
          array('picture', 'file', 'types' => 'jpg, gif, png,jpeg', 'allowEmpty' => true),
          array('id, authassignment,first_name, middle_name, last_name, username, password, email, picture, birthday, country, address, tele, fax, web, status,role,address2', 'safe', 'on' => 'search'),
      );
   }

   /**
    * @return array relational rules.
    */
   public function relations() {
      // NOTE: you may need to adjust the relation name and the related
      // class name for the relations automatically generated below.
      return array(
          'Authitem' => array(self::MANY_MANY, 'Authitem', 'authassignment(userid, itemname)'),
              //'authassignment' => array(self::BELONGS_TO, 'Authassignment', 'userid'),
      );
   }

   /**
    * @return array customized attribute labels (name=>label)
    */
   public function attributeLabels() {
      return array(
          'id' => 'ID',
          'first_name' => 'First Name',
          'middle_name' => 'Middle Name',
          'last_name' => 'Last Name',
          'username' => 'Username',
          'new_password' => 'New Password',
          'repeat_password' => 'Repeat Password',
          'assignItem' => 'Assign Item',
          'password' => 'Password',
          'email' => 'Email',
          'picture' => 'Picture',
          'birthday' => 'Birthday',
          'country' => 'Country',
          'address' => 'Address',
          'address2' => 'Address2',
          'tele' => 'Tele',
          'fax' => 'Fax',
          'web' => 'Web',
          'status' => 'Status',
      );
   }

   public function search() {
      $criteria = new CDbCriteria;
      $criteria->select = 't.id, GROUP_CONCAT(a.itemname) as role, t.first_name, t.username, t.email, t.address, t.tele, t.country, t.status';
      $criteria->join = 'LEFT JOIN authassignment a ON t.id = a.userid LEFT JOIN authitem m ON m.name = a.itemname';
      $criteria->group = 't.email';
      $criteria->order = 't.id';

      if (Yii::app()->user->checkAccess('admin')) {
         // $criteria->condition = 'a.itemname IN (\'users\') ';
      } else if (Yii::app()->user->checkAccess('users')) {
         // $criteria->condition = 'a.itemname NOT IN (\'SUPPERADMIN\', \'admin\')';
      }


      $criteria->compare('id', $this->id);
      $criteria->compare('first_name', $this->first_name, true);
      $criteria->compare('middle_name', $this->middle_name, true);
      $criteria->compare('last_name', $this->last_name, true);
      $criteria->compare('username', $this->username, true);
      $criteria->compare('password', $this->password, true);
      $criteria->compare('email', $this->email, true);
      $criteria->compare('picture', $this->picture, true);
      $criteria->compare('birthday', $this->birthday, true);
      $criteria->compare('country', $this->country, true);
      $criteria->compare('address', $this->address, true);
      $criteria->compare('address2',$this->address2,true);
      $criteria->compare('tele', $this->tele, true);
      $criteria->compare('fax', $this->fax, true);
      $criteria->compare('web', $this->web, true);
      $criteria->compare('status', $this->status, true);
      $criteria->compare('authitems.name', $this->role, true);
      //print_r($criteria);exit;
      return new CActiveDataProvider($this, array(
                  'pagination' => array(
                      'pageSize' => 10,
                  ),
                  'criteria' => $criteria,
              ));
   }

   public function encryptPassword($password) {
      return md5(md5($password) . Yii::app()->params['passwordSalt']);
   }

   public function validatePassword($password) {
      return $this->encryptPassword($password) == $this->password;
   }

   public function ShowAllRolesUsers($id) {

      $roles = Rights::getAssignedRoles($id);
      $users = array();
      foreach ($roles as $role)
         $users[] = $role->name;

      $this->role = implode(",", $users);
      // return implode(",", $users);
   }
   /*
    * create image derectories for upload user image
    */

   public function createImageDirectories($id) {

      $path = array();
      $imagePath = Yii::app()->params['imageSavePath'];
      //print_r($imagePath);exit;

      if (!is_dir($imagePath)) {
         if (!mkdir($imagePath, 0755, true)) {
            throw new CHttpException(500, 'Could not create the directory structure for user image.');
         }
      }
      if (!is_dir($imagePath . DIRECTORY_SEPARATOR . $id)) {
         if (mkdir($imagePath . DIRECTORY_SEPARATOR . $id))
            mkdir($imagePath . DIRECTORY_SEPARATOR . $id . DIRECTORY_SEPARATOR . 'thumbnail');
      }

      $path['thumbnail'] = $id . DIRECTORY_SEPARATOR . 'thumbnail';
      return $path;
   }
   /*
    * function for create random string
    */

   public static function generateRandomString($length = 32) {
      $chars = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
      shuffle($chars);
      return implode('', array_slice($chars, 0, $length));
   }

   public function loadModel($id) {
      $model = $this->model()->findByPk($id);
      if ($model === null)
         throw new CHttpException(404, 'The requested page does not exist.');
      return $model;
   }
}